package lesson03.TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.Socket;
import java.util.Scanner;

public class TCPEchoClient01 {

    private Socket socket;


    public TCPEchoClient01(String serverId, int serverPort) throws IOException {
        if (serverId == null || serverId.isEmpty()) {
            throw new BindException("服务器id不能为空");
        }
        if (serverPort < 1025 || serverPort > 65535) {
            throw new RuntimeException("端口号必须在1025 ~ 65535之间.");
        }
        socket = new Socket(serverId, serverPort);//自动分配服务器的ip地址与端口号

    }

    public void start() {
        System.out.println("客户端已启动.");
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()) {
            while (true) {
                System.out.println("->");
                Scanner scanner = new Scanner(System.in);
                String request = scanner.nextLine();
                if (request == null || request.isEmpty()) {
                    System.out.println("输入的内容不能为空");
                    continue;
                }
                PrintWriter writer = new PrintWriter(outputStream);
                writer.println(request);
                writer.flush();

                Scanner responseScanner = new Scanner(inputStream);
                String response = responseScanner.nextLine();
                System.out.printf("request = %s response = %s\n", request, response);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TCPEchoClient01 tcpEchoClient = new TCPEchoClient01("127.0.0.1", 9090);
        tcpEchoClient.start();
    }
}
